package top.canyue.word_range_service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import top.canyue.word_range.constant.StageConstant;
import top.canyue.word_range.exception.BaseException;
import top.canyue.word_range.pojo.buider.ReviewBuilder;
import top.canyue.word_range.pojo.dto.LoginUser;
import top.canyue.word_range.pojo.po.Review;
import top.canyue.word_range.pojo.po.WordMapping;
import top.canyue.word_range.result.Result;
import top.canyue.word_range.utils.StageUtil;
import top.canyue.word_range_service.mapper.ReviewMapper;
import top.canyue.word_range_service.service.ReviewService;

import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class ReviewServiceImpl extends ServiceImpl<ReviewMapper, Review> implements ReviewService {
    private final ReviewMapper reviewMapper;

    private void validateBookId(String bookId) {
        if (Objects.equals(bookId, "")) throw new BaseException("请选择词书后操作");
    }

    private String getUserIdFromSecurityContext() {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder
                .getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser.getUser().getId();
    }

    @Override
    public Result<Review> saveOrUpdateReview(String word) {
        // 通过JWT获得UserID
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder
                .getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = loginUser.getUser().getId();
        // 更新数据
        if (userId == null || word == null) throw new BaseException("用户ID与单词不得为空");
        LambdaQueryWrapper<Review> eq = new LambdaQueryWrapper<Review>()
                .eq(Review::getUserId, userId)
                .eq(Review::getWord, word);
        Review existingReview = reviewMapper.selectOne(eq);
        if (existingReview != null) {
            /// @see: top.canyue.word_range.utils.StageUtil#updateReview(Review)
            Review review = StageUtil.updateReview(existingReview);
            reviewMapper.updateById(review);
        }else{
            /// @see: top.canyue.word_range.pojo.buider.ReviewBuilder#buildReview(String, String)
            Review review = ReviewBuilder.buildReview(userId, word);
            reviewMapper.insert(review);
        }
        return Result.success();
    }


    @Override
    public Result<List<WordMapping>> getRandomReviewWordList(String bookId, Integer count) {
        validateBookId(bookId);
        if (count == null) count = 10;
        String userId = getUserIdFromSecurityContext();
        return Result.success(reviewMapper.getRandomReviewWordList(userId, bookId, count));
    }

    @Override
    public Result<List<WordMapping>> getRandomNewWordList(String bookId, Integer count){
        validateBookId(bookId);
        if (count == null) count = 5;
        String userId = getUserIdFromSecurityContext();
        return Result.success(reviewMapper.getRandomNewWordList(userId, bookId, count));
    }

    @Override
    public Result<List<WordMapping>> getRandomReviewWordListByEvent(Integer count){
        if (count == null) count = 10;
        String userId = getUserIdFromSecurityContext();
        return Result.success(reviewMapper.getRandomReviewWordListByEvent(userId, count));
    }

    @Override
    public Result<Long> getReviewedWordCount(String jwt) {
        if (jwt == null) throw new BaseException("请登录后操作");
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder
                .getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String loginUserId = loginUser.getUser().getId();
        if (loginUserId != null) {
            LambdaQueryWrapper<Review> eq = new LambdaQueryWrapper<Review>()
                    .eq(Review::getUserId, loginUserId);
            Long count = reviewMapper.selectCount(eq);
            return Result.success(count);
        }
        return Result.error("获取失败");
    }

    @Override
    public Result<Long> getMasteredWordCount(String jwt) {
        if (jwt == null) throw new BaseException("请登录后操作");
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder
                .getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String loginUserId = loginUser.getUser().getId();
        if (loginUserId != null) {
            LambdaQueryWrapper<Review> eq = new LambdaQueryWrapper<Review>()
                    .eq(Review::getUserId, loginUserId)
                    .eq(Review::getStage, StageConstant.HAVE_MASTERED);
            Long count = reviewMapper.selectCount(eq);
            return Result.success(count);
        }
        return Result.error("获取失败");
    }

}
